package com.wjc.server.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.ChapterDto;
import com.wjc.server.dto.ChapterPageDto;
import com.wjc.server.entity.Chapter;
import com.wjc.server.entity.ChapterExample;
import com.wjc.server.mapper.ChapterMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChapterService {
    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private SnowFlake snowFlake;

    public void list(ChapterPageDto chapterPageDto){
        PageHelper.startPage(chapterPageDto.getPage(),chapterPageDto.getSize());

        ChapterExample chapterExample = new ChapterExample();
        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        //若courseid不为空，则按照courseid查询。
        if(!ObjectUtils.isEmpty(chapterPageDto.getCourseId())){
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }

        List<Chapter> chapterList= chapterMapper.selectByExample(chapterExample);
        PageInfo<Chapter> pageInfo=new PageInfo<>(chapterList);
        chapterPageDto.setTotal(pageInfo.getTotal());

        List<ChapterDto> chapterDtosList = CopyUtil.copyList(chapterList,ChapterDto.class);
        chapterPageDto.setList(chapterDtosList);

    }

    public void save(ChapterDto chapterDto){
        Chapter chapter=CopyUtil.copy(chapterDto,Chapter.class);
        if (ObjectUtils.isEmpty(chapter.getId())){
            //新增
            chapter.setId(snowFlake.nextId());
            chapterMapper.insert(chapter);
        }else {
            chapterMapper.updateByPrimaryKey(chapter);
        }

    }

    public void delete(Long id){
        chapterMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询某一课程下的所有章
     */
    public List<ChapterDto> listByCourse(Long courseId) {
        ChapterExample example = new ChapterExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Chapter> chapterList = chapterMapper.selectByExample(example);
        List<ChapterDto> chapterDtoList = CopyUtil.copyList(chapterList, ChapterDto.class);
        return chapterDtoList;
    }
}
